"""
配置文件
"""

import os
import json
from typing import List
from pathlib import Path


class Settings:
    """应用配置"""

    APP_NAME: str = "网络调试助手API"
    VERSION: str = "1.0.0"
    HOST: str = "0.0.0.0"
    PORT: int = 20001  # 默认端口改为20001

    # CORS配置
    CORS_ORIGINS: List[str] = ["*"]  # 在生产环境中应该设置具体的域名
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: List[str] = ["*"]
    CORS_ALLOW_HEADERS: List[str] = ["*"]

    # WebSocket配置
    WEBSOCKET_PING_INTERVAL: float = 0.1
    WEBSOCKET_TIMEOUT: int = 60

    # 静态文件配置
    STATIC_DIR: str = "static"

    # 配置文件路径
    CONFIG_FILE: str = "/etc/net-tools/config.json"

    def __init__(self):
        """初始化配置，从配置文件加载"""
        self.load_config()

    def load_config(self):
        """从配置文件加载配置"""
        try:
            if os.path.exists(self.CONFIG_FILE):
                with open(self.CONFIG_FILE, "r", encoding="utf-8") as f:
                    config_data = json.load(f)
                    self.PORT = config_data.get("port", self.PORT)
                    self.HOST = config_data.get("host", self.HOST)
        except Exception as e:
            print(f"警告：加载配置文件失败: {e}，使用默认配置")

    def save_config(self):
        """保存配置到文件"""
        try:
            # 确保配置目录存在
            config_dir = os.path.dirname(self.CONFIG_FILE)
            os.makedirs(config_dir, exist_ok=True)

            config_data = {"port": self.PORT, "host": self.HOST}

            with open(self.CONFIG_FILE, "w", encoding="utf-8") as f:
                json.dump(config_data, f, indent=2, ensure_ascii=False)

            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False

    def update_port(self, new_port: int) -> bool:
        """更新端口配置"""
        if 1 <= new_port <= 65535:
            self.PORT = new_port
            return self.save_config()
        return False


settings = Settings()
